"""
@Time: 2021/2/5 下午 8:35
@Author: jinzhuan
@File: bert_capsule.py
@Desc: 
"""

import sys
sys.path.append('/data/zhuoran/code/cognlp')
sys.path.append('/data/zhuoran/cognlp')

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import RandomSampler
from cognlp import *
from cognlp.core.metrics import ClassifyFPreRecMetric
from cognlp.models.re.bert_capsule import Bert4Capsule
from cognlp.io.processor.re.deepke import DeepkeRelationProcessor
from cognlp.io.loader.re.deepke import CsvRelationLoader


torch.cuda.set_device(6)
device = torch.device('cuda')
vocabulary = Vocabulary.load('../../../cognlp/data/re/csv/vocabulary.txt')

loader = CsvRelationLoader()
train_data, dev_data, test_data = loader.load_all('../../../cognlp/data/re/csv')

processor = DeepkeRelationProcessor(path='../../../cognlp/data/re/csv')

train_data = processor.process(train_data)
dev_data = processor.process(dev_data)
test_data = processor.process(test_data)

train_dataset = DataTableSet(train_data)
dev_dataset = DataTableSet(dev_data)
test_dataset = DataTableSet(test_data)

train_sampler = RandomSampler(train_dataset)
dev_sampler = RandomSampler(dev_dataset)
test_sampler = RandomSampler(test_dataset)

model = Bert4Capsule(vocabulary, bert_model='hfl/chinese-roberta-wwm-ext')
metric = ClassifyFPreRecMetric()
loss = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.00005)

trainer = Trainer(model,
                  train_dataset,
                  dev_data=dev_dataset,
                  n_epochs=30,
                  batch_size=20,
                  loss=loss,
                  optimizer=optimizer,
                  scheduler=None,
                  metrics=metric,
                  train_sampler=train_sampler,
                  dev_sampler=dev_sampler,
                  drop_last=False,
                  gradient_accumulation_steps=1,
                  num_workers=5,
                  save_path='../../../cognlp/data/re/csv/model',
                  save_file=None,
                  print_every=None,
                  scheduler_steps=None,
                  validate_steps=None,
                  save_steps=None,
                  grad_norm=None,
                  use_tqdm=True,
                  device=device,
                  device_ids=[6],
                  callbacks=None,
                  metric_key=None,
                  writer_path='../../../cognlp/data/re/csv/tensorboard',
                  fp16=False,
                  fp16_opt_level='O1',
                  task='baidu',
                  logger_path='../../../cognlp/data/re/csv/logger')

trainer.train()
